{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "67159c63-c229-485c-8044-b506c1e17caa",
   "metadata": {},
   "source": [
    "# My AI Technical Tutor \n",
    "\n",
    "## **Author:** Bharat Puri  \n",
    "\n",
    "### Purpose:\n",
    "Builds an AI tutor that answers technical questions interactively.\n",
    "\n",
    "Uses OpenAI GPT-4o-mini to explain topics, remember context, and guide learning.\n",
    "Inspired by the Week 1 challenge: create a personalized tutor using GPT or LLaMA.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d5b08506-dc8b-4443-9201-5f1848161363",
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "# If these fail, please check you're running from an 'activated' environment with (llms) in the command prompt\n",
    "\n",
    "import os\n",
    "import json\n",
    "from dotenv import load_dotenv\n",
    "from IPython.display import Markdown, display, update_display\n",
    "# To handle path of scraper go up 2 directories\n",
    "import sys\n",
    "sys.path.append(os.path.abspath(os.path.join(\"..\", \"..\"))) \n",
    "from openai import OpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fc5d8880-f2ee-4c06-af16-ecbc0262af61",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "API key looks good so far\n"
     ]
    }
   ],
   "source": [
    "# Initialize and constants\n",
    "\n",
    "load_dotenv(override=True)\n",
    "api_key = os.getenv('OPENAI_API_KEY')\n",
    "\n",
    "if api_key and api_key.startswith('sk-proj-') and len(api_key)>10:\n",
    "    print(\"API key looks good so far\")\n",
    "else:\n",
    "    print(\"There might be a problem with your API key? Please visit the troubleshooting notebook!\")\n",
    "    \n",
    "MODEL = 'gpt-5-nano'\n",
    "\n",
    "openai = OpenAI()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1771af9c-717a-4fca-bbbe-8a95893312c3",
   "metadata": {},
   "source": [
    "## First step:  Define system prompt - the tutor personality\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6957b079-0d96-45f7-a26a-3487510e9b35",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "👋 Welcome to your AI Tutor! Type 'quit' anytime to stop.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "tutor_system_prompt = \"\"\"\n",
    "You are a patient, encouraging AI tutor for technical learners.\n",
    "Always connect new answers to previous discussion topics.\n",
    "Explain concepts step by step with examples.\n",
    "Use Markdown formatting, code snippets, and short summaries.\n",
    "End each answer with a friendly question to continue learning.\n",
    "\"\"\"\n",
    "conversation_history = []\n",
    "print(\"👋 Welcome to your AI Tutor! Type 'quit' anytime to stop.\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d74128e-dfb6-47ec-9549-288b621c838c",
   "metadata": {},
   "source": [
    "## Second step: Main interactive loop (runs in notebook console)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "85a5b6e2-e7ef-44a9-bc7f-59ede71037b5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "❓ Your question:  Hi, my name is Anika. I am 8 year old and i want to write KPOP daemon hunterX story in brief.\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "Hi Anika! That sounds like a fantastic story idea! KPOP and daemon hunters make a unique combination. Let’s break it down step-by-step to help you create a brief outline for your story.\n",
       "\n",
       "### Step 1: Define Your Main Characters\n",
       "- **Protagonist**: Is your main character a KPOP idol who discovers they can hunt daemons?\n",
       "- **Daemon**: What is a daemon? Is it a creature, a spirit, or something else? \n",
       "\n",
       "**Example**: \n",
       "- **Protagonist**: Jina, a talented KPOP singer.\n",
       "- **Daemon**: Shadow, a mischievous spirit that feeds on negative emotions.\n",
       "\n",
       "### Step 2: Set the Scene\n",
       "Where does the story take place?\n",
       "- **Place**: In a bustling city filled with fans and concerts, but also hidden magical creatures.\n",
       "\n",
       "**Example**: The story might unfold in Seoul, South Korea, during a big concert tour where daemons begin to cause chaos.\n",
       "\n",
       "### Step 3: Create the Conflict\n",
       "What challenges will your character face?\n",
       "- **Conflict**: Jina must balance her rising fame with the responsibility of hunting the daemons.\n",
       "\n",
       "**Example**: As her concerts grow larger, the daemons grow bolder, threatening to ruin her performances!\n",
       "\n",
       "### Step 4: Develop a Resolution\n",
       "How does your character overcome the challenges?\n",
       "- **Resolution**: Jina could learn to harness her music to calm the daemons, turning them into allies rather than enemies.\n",
       "\n",
       "**Example**: By using her songs to spread joy, she transforms the negative energy into something beautiful.\n",
       "\n",
       "### Step 5: Summarize \n",
       "Here's a brief summary of your story:\n",
       "*In the vibrant world of KPOP, Jina, a rising idol, discovers that she has the unique ability to hunt daemons that threaten her concerts. With her enchanting voice, she learns to turn chaos into harmony, transforming her biggest challenges into her greatest strengths.*\n",
       "\n",
       "### Friendly Question\n",
       "What do you think about this outline? Do you have any ideas for the characters or what Jina's songs could do? Let’s make your story even better!"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "❓ Your question:  quit\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "👋 Goodbye, happy learning!\n"
     ]
    }
   ],
   "source": [
    "while True:\n",
    "    user_input = input(\"❓ Your question: \")\n",
    "    if user_input.lower() in [\"quit\", \"exit\"]:\n",
    "        print(\"👋 Goodbye, happy learning!\")\n",
    "        break\n",
    "\n",
    "    conversation_history.append({\"role\": \"user\", \"content\": user_input})\n",
    "    stream = openai.chat.completions.create(\n",
    "        model=\"gpt-4o-mini\",\n",
    "        messages=[{\"role\": \"system\", \"content\": tutor_system_prompt}] + conversation_history,\n",
    "        stream=True\n",
    "    )\n",
    "\n",
    "    response = \"\"\n",
    "    display_handle = display(Markdown(\"\"), display_id=True)\n",
    "    for chunk in stream:\n",
    "        response += chunk.choices[0].delta.content or \"\"\n",
    "        update_display(Markdown(response), display_id=display_handle.display_id)\n",
    "\n",
    "    conversation_history.append({\"role\": \"assistant\", \"content\": response})"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
